package com.superhelper.common.service;

import java.util.Properties;

import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.ONSFactory;
import com.aliyun.openservices.ons.api.Producer;
import com.aliyun.openservices.ons.api.PropertyKeyConst;
import com.aliyun.openservices.ons.api.SendResult;
import com.superhelper.common.Consts;
import com.superhelper.common.domain.AuserShop;
import com.superhelper.common.domain.TakeOutOrderType;
import com.superhelper.common.domain.User;
import com.superhelper.common.domain.baidu.BdPushEntity;
import com.superhelper.common.domain.dada.DaDaCallback;
import com.superhelper.common.domain.ele.ElePushEntity;
import com.superhelper.common.domain.mt.MtOrderPushEntity;
import com.superhelper.common.mapper.TakeOutOrderMapper;
import com.superhelper.common.utils.JsonHelper;

public final class AliMQProducerService {
    private static final Logger log = LoggerFactory.getLogger(AliMQProducerService.class);

    private volatile Producer orderProducer = null;
    // private volatile Producer eleProducer = null;
    // private volatile Producer mtProducer = null;
    // private volatile Producer bdProducer = null;
    // private volatile Producer dadaProducer = null;
    //
    // private Object eleMonitor = new Object();
    // private Object mtMonitor = new Object();
    // private Object bdMonitor = new Object();
    private Object orderMonitor = new Object();
    @Value("${aliyun.access.key}")
    private String aliyunAccessKey;
    @Value("${aliyun.access.secret}")
    private String aliyunSecretKey;

    // @Value("${mt.order.producer.id}")
    // private String mtProducerId;
    // @Value("${mt.order.topic}")
    // private String mtOrderTopic;
    //
    // @Value("${ele.order.producer.id}")
    // private String eleProducerId;
    // @Value("${ele.order.topic}")
    // private String eleOrderTopic;
    //
    // @Value("${bd.order.producer.id}")
    // private String bdProducerId;
    // @Value("${bd.order.topic}")
    // private String bdOrderTopic;
    //
    // @Value("${dada.topic}")
    // private String dadaTopic;
    //
    // @Value("${dada.producer.id}")
    // private String dadaProducerId;

    @Value("${order.topic}")
    private String orderTopic;

    @Value("${order.producer.id}")
    private String orderProducerId;

    @Value("${online}")
    private boolean online;
    @Autowired
    private TakeOutOrderMapper orderMapper;

    // public Producer getEleOrderProducer() {
    // if (eleProducer == null) {
    // synchronized (eleMonitor) {
    // if (eleProducer == null) {
    // Properties properties = new Properties();
    // properties.put(PropertyKeyConst.AccessKey, aliyunAccessKey);
    // properties.put(PropertyKeyConst.SecretKey, aliyunSecretKey);
    // properties.put(PropertyKeyConst.ProducerId, eleProducerId);
    // eleProducer = ONSFactory.createProducer(properties);
    // eleProducer.start();
    // }
    // }
    // }
    // return eleProducer;
    // }
    //
    // public Producer getMtOrderProducer() {
    // if (mtProducer == null) {
    // synchronized (mtMonitor) {
    // if (mtProducer == null) {
    // Properties properties = new Properties();
    // properties.put(PropertyKeyConst.AccessKey, aliyunAccessKey);
    // properties.put(PropertyKeyConst.SecretKey, aliyunSecretKey);
    // properties.put(PropertyKeyConst.ProducerId, mtProducerId);
    // mtProducer = ONSFactory.createProducer(properties);
    // mtProducer.start();
    // }
    // }
    // }
    // return mtProducer;
    // }
    //
    // public Producer getBdOrderProducer() {
    // if (bdProducer == null) {
    // synchronized (bdMonitor) {
    // if (bdProducer == null) {
    // Properties properties = new Properties();
    // properties.put(PropertyKeyConst.AccessKey, aliyunAccessKey);
    // properties.put(PropertyKeyConst.SecretKey, aliyunSecretKey);
    // properties.put(PropertyKeyConst.ProducerId, bdProducerId);
    // bdProducer = ONSFactory.createProducer(properties);
    // bdProducer.start();
    // }
    // }
    // }
    // return bdProducer;
    // }
    //
    // public Producer getDadaProducer() {
    // if (dadaProducer == null) {
    // synchronized (eleMonitor) {
    // if (dadaProducer == null) {
    // Properties properties = new Properties();
    // properties.put(PropertyKeyConst.AccessKey, aliyunAccessKey);
    // properties.put(PropertyKeyConst.SecretKey, aliyunSecretKey);
    // properties.put(PropertyKeyConst.ProducerId, dadaProducerId);
    // dadaProducer = ONSFactory.createProducer(properties);
    // dadaProducer.start();
    // }
    // }
    // }
    // return dadaProducer;
    // }

    public Producer getOrderProducer() {
        if (orderProducer == null) {
            synchronized (orderMonitor) {
                if (orderProducer == null) {
                    Properties properties = new Properties();
                    properties.put(PropertyKeyConst.AccessKey, aliyunAccessKey);
                    properties.put(PropertyKeyConst.SecretKey, aliyunSecretKey);
                    properties.put(PropertyKeyConst.ProducerId, orderProducerId);
                    orderProducer = ONSFactory.createProducer(properties);
                    orderProducer.start();
                }
            }
        }
        return orderProducer;
    }

    public boolean sendEleOrder(ElePushEntity entity) {
        String tag = orderTopic + online + "-ele";
        Message msg = new Message(orderTopic, tag, JsonHelper.toJson(entity).getBytes(Consts.UTF8_CHARSET));
        msg.setKey("ele-" + entity.getRequestId());
        String shopId = String.valueOf(entity.getShopId());
        AuserShop shop = orderMapper.getShop(shopId, TakeOutOrderType.EleMe.getValue());

        if (shop != null) {
            User user = orderMapper.getUserPackageName(shop.getAuserId());
            Long time = System.currentTimeMillis();
            if ("com.superhelper.superaide".equals(user.getSource()) && user.getCreateAt().getTime() - time > 0) {
                SendResult sr = getOrderProducer().send(msg);
                String msgId = sr.getMessageId();
                log.info("[sendEleOrder] success, key:{},msgId:{}", msg.getKey(), msgId);
            } else if ("com.superhelper".equals(user.getSource())) {
                SendResult sr = getOrderProducer().send(msg);
                String msgId = sr.getMessageId();
                log.info("[sendEleOrder] success, key:{},msgId:{}", msg.getKey(), msgId);
            }
        } else {
            log.info("[sendEleOrder]  user expire not send , shopId:{}", shopId);
        }
        return true;
    }

    public boolean sendMtOrder(Long orderId, String pushType, MtOrderPushEntity entity) {
        String tag = orderTopic + online + "-mt";
        entity.setPushType(pushType);
        Message msg = new Message(orderTopic, tag, JsonHelper.toJson(entity).getBytes(Consts.UTF8_CHARSET));
        msg.setKey("mt-" + orderId);
        String shopId = entity.getePoiId();
        AuserShop shop = orderMapper.getShop(shopId, TakeOutOrderType.MeiTuan.getValue());
        if (shop != null) {
            User user = orderMapper.getUserPackageName(shop.getAuserId());
            Long time = System.currentTimeMillis();
            if ("com.superhelper.superaide".equals(user.getSource()) && user.getCreateAt().getTime() - time > 0) {
                SendResult sr = getOrderProducer().send(msg);
                String msgId = sr.getMessageId();
                log.info("[sendMtOrder]  success, key:{},msgId:{}", msg.getKey(), msgId);
            } else if ("com.superhelper".equals(user.getSource())) {
                SendResult sr = getOrderProducer().send(msg);
                String msgId = sr.getMessageId();
                log.info("[sendMtOrder] success, key:{},msgId:{}", msg.getKey(), msgId);
            }
        } else {
            log.info("[sendMtOrder]  user expire not send , shopId:{}", shopId);
        }
        return true;
    }

    public boolean sendBdOrder(BdPushEntity entity) {
        String tag = orderTopic + online + "-bd";
        Message msg = new Message(orderTopic, tag, JsonHelper.toJson(entity).getBytes(Consts.UTF8_CHARSET));
        msg.setKey("bd-" + entity.getSign());
        SendResult sr = getOrderProducer().send(msg);
        String msgId = sr.getMessageId();
        log.info("[sendBdOrder]  success, key:{},msgId:{}", msg.getKey(), msgId);
        return true;
    }

    @PreDestroy
    public void destroy() {
        // if (mtProducer != null) {
        // mtProducer.shutdown();
        // }
        // if (eleProducer != null) {
        // eleProducer.shutdown();
        // }
        // if (bdProducer != null) {
        // bdProducer.shutdown();
        // }
        // if (dadaProducer != null) {
        // dadaProducer.shutdown();
        // }
        if (orderProducer != null) {
            orderProducer.shutdown();
        }
    }

    public boolean sendDada(DaDaCallback cb) {
        String tag = orderTopic + online + "-dada";
        Message msg = new Message(orderTopic, tag, JsonHelper.toJson(cb).getBytes(Consts.UTF8_CHARSET));
        // 就算有重复消息也再发一遍，所有key选择加上毫秒数
        msg.setKey("dada-" + cb.getOrder_id() + "-" + System.currentTimeMillis());
        SendResult sr = getOrderProducer().send(msg);
        String msgId = sr.getMessageId();
        log.info("[sendDada]  success, key:{},msgId:{}", msg.getKey(), msgId);
        return true;
    }
}
